package com.buddies.lottery.ui.pay;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.buddies.lottery.App;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseActivity;
import com.buddies.lottery.common.ConfigManager;
import com.buddies.lottery.common.Constants;
import com.buddies.lottery.data.resp.PayResponse;
import com.buddies.lottery.data.resp.PayResultResponse;
import com.buddies.lottery.ui.pay.record.PayRecordActivity;
import com.buddies.lottery.utils.CopyUtils;
import com.buddies.lottery.utils.LotteryUtils;
import com.buddies.lottery.utils.QRCodeEncoder;
import com.r0adkll.slidr.Slidr;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chandler on 16/3/15.
 */
public class PayActivity extends BaseActivity<PayContract.Presenter> implements PayContract.View {

    private TextView btnPayRecord;

    protected SwipeRefreshLayout mSwipeRefreshLayout;
    protected Map<String, String> mPayQrcodes = new HashMap<>();

    public TextView tv_balance;
    public ImageView iv_wechat_selected;
    public ImageView iv_ali_selected;
    public FrameLayout fl_wechat;
    public FrameLayout fl_ali;
    public EditText etMoney;
    public View btnCommit;

    private String mPayType;
    private String mPayQrcode;
    private String mOrderNo;
    private int mPayMoney;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Slidr.attach(this, App.getSlidrConfig());
    }

    @Override
    protected void initView() {
        setUp();
        setTitle("充值");

        btnPayRecord = findViewById(R.id.tv_action);
        btnPayRecord.setVisibility(View.VISIBLE);
        btnPayRecord.setText("交易记录");
        btnPayRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PayRecordActivity.launch(getActivity()); // 充值记录
            }
        });

        mSwipeRefreshLayout = findViewById(R.id.refresher);

        tv_balance = findViewById(R.id.tv_balance);
        iv_wechat_selected = findViewById(R.id.iv_wechat_selected);
        iv_ali_selected = findViewById(R.id.iv_ali_selected);
        fl_wechat = findViewById(R.id.fl_wechat);
        fl_ali = findViewById(R.id.fl_ali);

        etMoney = findViewById(R.id.et_money);
        btnCommit = findViewById(R.id.btn_commit);
    }

    @Override
    protected void initData() {
        mPresenter = new PayPresenter(this);

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                forceRefresh();
            }
        });

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int pos) {
                if (pos == 0) {
                    return 3;
                } else {
                    return 1;
                }
            }
        });

        mPayType = SPUtils.getInstance().getString("payType", Constants.PayType.ALIPAY);
        tv_balance.setText(LotteryUtils.formatBalance(ConfigManager.getInstance().getBalance()));
        fl_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSelectPayMethod(Constants.PayType.WECHAT_PAY);
            }
        });
        fl_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSelectPayMethod(Constants.PayType.ALIPAY);
            }
        });
        onSelectPayMethod(mPayType);

        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                btnCommit.setEnabled(etMoney.getText().length() > 0);
            }
        });

        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayMoney = Integer.parseInt(etMoney.getText().toString());
                doPay();
            }
        });

        forceRefresh();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    /**
     * 选择支付方式
     *
     * @param payType 支付方式，0代表微信支付， 1代表支付宝支付
     */
    private void onSelectPayMethod(String payType) {
        mPayType = payType;
        if (Constants.PayType.WECHAT_PAY.equals(payType)) {
            iv_ali_selected.setVisibility(View.GONE);
            iv_wechat_selected.setVisibility(View.VISIBLE);
        } else if (Constants.PayType.ALIPAY.equals(payType)) {
            iv_ali_selected.setVisibility(View.VISIBLE);
            iv_wechat_selected.setVisibility(View.GONE);
        }
        SPUtils.getInstance().put("payType", payType);
    }

    public void forceRefresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(true);

                    mPresenter.loadPayQrcode();
                }
            });
        }
    }

    @Override
    public void onPaySuccess(final PayResultResponse response) {
        hideProgressDialog();

        final String orderNo = response.order_no;
        String message = String.format("请在转账时输入金额: %s 元和备注: %s，否则无法充值成功，充值成功后仍未到账请联系客服！", mPayMoney, orderNo);
        SpannableStringBuilder builder = new SpannableStringBuilder(message);

        int index = message.indexOf(":");
        int length = String.valueOf(mPayMoney).length();
        while (index > 0) {
            int start = index + 2;
            int end = start + length;

            builder.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.setSpan(new AbsoluteSizeSpan(ConvertUtils.sp2px(22)), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            index = message.indexOf(":", end);
            length = orderNo.length();
        }

        Bitmap bitmap = QRCodeEncoder.encodeQRcode(mPayQrcode);

        // 保存二维码到本地
        String fileName = String.format("%s_%s.png", mPayType, mPayMoney);
        String dirPath = Environment.getExternalStorageDirectory() + "/Buddies/";
        FileUtils.createOrExistsDir(dirPath);

        final String filePath = dirPath + fileName;

        long lastModified = FileUtils.getFileLastModified(filePath);
        if (bitmap != null && System.currentTimeMillis() - lastModified > 10 * 1000) {
            byte[] bytes = ImageUtils.bitmap2Bytes(bitmap, Bitmap.CompressFormat.PNG);
            boolean result = FileIOUtils.writeFileFromBytesByStream(filePath, bytes);
            if (result) {
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(filePath))));
            }
        }

        View container = LayoutInflater.from(getActivity()).inflate(R.layout.item_pay_post, null);

        final ImageView image = container.findViewById(R.id.image);
        image.setImageBitmap(bitmap);

        final TextView text = container.findViewById(R.id.text);
        text.setText(builder);

        new AlertDialog.Builder(this)
                .setTitle("充值提示")
                .setView(container)
                .setPositiveButton("我知道了，去充值", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (FileUtils.isFileExists(filePath)) {
                            CopyUtils.copy(getActivity(), orderNo);
                            ToastUtils.showShort("转账备注已复制到剪贴板");

                            mOrderNo = orderNo;
                            openAlipayScan();
                        } else {
                            ToastUtils.showShort("保存二维码失败");
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

    @Override
    public void onPayQrcodeLoaded(PayResponse response) {
        mSwipeRefreshLayout.setRefreshing(false);

        mPayQrcodes.clear();
        if (response.qrcodes != null) {
            mPayQrcodes.putAll(response.qrcodes);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(mOrderNo)) {
            forceRefresh();

            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("充值提示")
                    .setPositiveButton("已完成充值", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            forceRefresh();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .setCancelable(false)
                    .create();
            alertDialog.setCanceledOnTouchOutside(false);
            alertDialog.show();
        }
    }

    public void doPay() {
        if (!ConfigManager.getInstance().isLogin()) {
            ToastUtils.showShort("用户信息出错，请重试");
            return;
        }

        if (mPayMoney < 0) {
            ToastUtils.showShort("充值金额不能小于0");
            return;
        }

        String qrcode = mPayQrcodes.get(mPayType);
        if (TextUtils.isEmpty(qrcode)) {
            ToastUtils.showShort(String.format("暂时不支持%s充值", getPayTypeName(mPayType)));
            return;
        }

        showProgressDialog("正在请求");
        mPayQrcode = qrcode;
        mPresenter.postPay(mPayType, String.valueOf(mPayMoney));
    }

    private String getPayTypeName(String payType) {
        return TextUtils.equals(payType, Constants.PayType.ALIPAY) ? "支付宝" : "微信";
    }

    public void openAlipayScan() {
        try {
            String uri = "alipays://platformapi/startapp?saId=10000007";
            Intent intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME);
            intent.setClassName("com.eg.android.AlipayGphone", "com.alipay.mobile.quinox.SchemeLauncherActivity");
            intent.addCategory(Intent.CATEGORY_APP_BROWSER);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            ToastUtils.showLong("请点击右上角相册选择最新的二维码完成转账");
        } catch (Exception e) {
            ToastUtils.showShort("请手动打开支付宝「扫一扫」");
        }
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        mSwipeRefreshLayout.setRefreshing(false);
    }

    public static void launch(Context context) {
        context.startActivity(new Intent(context, PayActivity.class));
    }
}
